// customer_service.c
#include "customer_service.h"
#include "json_process.h" // 包含cJSON处理


static lv_obj_t *chat_area; // 聊天显示区域
static lv_obj_t *input_ta;  // 输入框
static lv_obj_t *send_btn;  // 发送按钮
static lv_obj_t *back_btn;  // 返回按钮
static lv_obj_t *kb = NULL;
// static lv_obj_t *cand_panel;//中文候选框

lv_obj_t *people_scr=NULL;

lv_obj_t *customer_scr = NULL;

// DeepSeek API配置
#define DEEPSEEK_API_KEY "sk-d7cdae1ad86e40c193c60f6eee57cd61"


static void people_cb(void)
{
    people_scr=lv_obj_create(NULL);
    lv_obj_add_style(people_scr, &bg_style, 0);
    people_scr_ui();
    lv_scr_load(people_scr);
    
}

//输入框回调
static void ta_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *ta = lv_event_get_target(e);

    if(code == LV_EVENT_FOCUSED) {
        lv_keyboard_set_textarea(kb, ta);   /* 关联键盘 */
        lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_obj_move_foreground(kb);

        /* 把输入框底部贴到键盘顶部 */
        lv_coord_t kb_h = lv_obj_get_height(kb);
        lv_coord_t ta_h = lv_obj_get_height(ta);
        lv_obj_set_y(ta, LV_VER_RES - kb_h - ta_h);   /* 紧贴键盘上方 */
    }
    else if(code == LV_EVENT_DEFOCUSED) {
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);      /* 失焦隐藏键盘 */
    }
}

// 类似json_process.c中的get_Json函数，获取API响应
static char *get_deepseek_response(const char *user_input) {
    // 构建curl命令
    char command[2048];
    snprintf(command, sizeof(command), 
        "curl -k -X POST \"https://api.deepseek.com/chat/completions\" "
        "-H \"Content-Type: application/json\" "
        "-H \"Authorization: Bearer %s\" "
        "-d '{\"model\": \"deepseek-chat\", \"messages\": [{\"role\": \"system\", \"content\": \"你是个很积极会说话的英文客服助手，帮助用户解决购票等相关问题\"}, {\"role\": \"user\", \"content\": \"%s\"}], \"stream\": false}'",
        DEEPSEEK_API_KEY, user_input);
    
    // 执行命令并获取响应
    char *response_buf = malloc(4096);
    if (response_buf == NULL) {
        return NULL;
    }
    
    FILE *fp = popen(command, "r");
    if (fp == NULL) {
        free(response_buf);
        return NULL;
    }
    
    int ret_val = fread(response_buf, 1, 4096-1, fp);
    response_buf[ret_val] = '\0';
    pclose(fp);
    
    // 查找JSON开始位置
    char *json_start = strchr(response_buf, '{');
    if (json_start == NULL) {
        free(response_buf);
        return NULL;
    }
    
    // 提取纯JSON部分
    char *json_str = strdup(json_start);
    free(response_buf);
    
    return json_str;
}

// 解析DeepSeek API响应
static char *parse_deepseek_response(const char *json_response) 
{
    cJSON *root = cJSON_Parse(json_response);
    if (!root) {
        return NULL;
    }
    
    // 提取回复内容
    cJSON *choices = cJSON_GetObjectItem(root, "choices");
    if (choices && cJSON_IsArray(choices)) {
        cJSON *first_choice = cJSON_GetArrayItem(choices, 0);
        if (first_choice) {
            cJSON *message = cJSON_GetObjectItem(first_choice, "message");
            if (message) {
                cJSON *content = cJSON_GetObjectItem(message, "content");
                if (content && cJSON_IsString(content)) {
                    char *reply = strdup(content->valuestring);
                    cJSON_Delete(root);
                    return reply;
                }
            }
        }
    }
    
    cJSON_Delete(root);
    return NULL;
}

// 发送消息事件处理
static void send_msg_event_cb(lv_event_t *e) {
    const char *msg = lv_textarea_get_text(input_ta);
    if(strlen(msg) == 0) return;
    
    // 添加用户消息到聊天区域
    lv_obj_t *user_msg = lv_label_create(chat_area);
    lv_label_set_text_fmt(user_msg, "您: %s", msg);
    lv_obj_set_style_text_align(user_msg, LV_TEXT_ALIGN_RIGHT, 0);
    lv_obj_set_style_text_color(user_msg, lv_color_hex(0x007ACC), 0);
    lv_obj_set_style_text_font(user_msg, font_chinese, 0);
    lv_obj_set_width(user_msg, LV_PCT(100));
    
    // 清空输入框
    lv_textarea_set_text(input_ta, "");
    
    // 调用API获取回复
    char *response = get_deepseek_response(msg);
    if(response) {
        char *reply = parse_deepseek_response(response);
        free(response);
        
        if(reply) {
            // 添加AI回复到聊天区域
            lv_obj_t *ai_msg = lv_label_create(chat_area);
            lv_label_set_text_fmt(ai_msg, "客服: %s", reply);
            lv_obj_set_style_text_align(ai_msg, LV_TEXT_ALIGN_LEFT, 0);
            lv_obj_set_style_text_color(ai_msg, lv_color_hex(0x28A745), 0);
            lv_obj_set_style_text_font(ai_msg, font_chinese, 0);
            lv_obj_set_width(ai_msg, LV_PCT(100));
            free(reply);
        } else {
            // 显示解析错误
            lv_obj_t *error_msg = lv_label_create(chat_area);
            lv_label_set_text(error_msg, "客服: 抱歉，解析回复时出现问题");
            lv_obj_set_style_text_align(error_msg, LV_TEXT_ALIGN_LEFT, 0);
            lv_obj_set_style_text_color(error_msg, lv_color_hex(0xFF5555), 0);
            lv_obj_set_style_text_font(error_msg, font_chinese, 0);
            lv_obj_set_width(error_msg, LV_PCT(100));
        }
    } else {
        // 显示连接错误
        lv_obj_t *error_msg = lv_label_create(chat_area);
        lv_label_set_text(error_msg, "客服: 抱歉，暂时无法连接客服，请稍后再试");
        lv_obj_set_style_text_align(error_msg, LV_TEXT_ALIGN_LEFT, 0);
        lv_obj_set_style_text_color(error_msg, lv_color_hex(0xFF5555), 0);
        lv_obj_set_style_text_font(error_msg, font_chinese, 0);
        lv_obj_set_width(error_msg, LV_PCT(100));
    }
    
    // 滚动到底部
    lv_obj_scroll_to_y(chat_area, lv_obj_get_scroll_bottom(chat_area), LV_ANIM_ON);
}

// 返回主界面
static void return_to_main_cb(lv_event_t *e) 
{
    lv_scr_load(scr_main);
}

// 联系客服界面
void show_customer_service_screen(void) 
{
    if(customer_scr) {
        lv_scr_load(customer_scr);
        return;
    }
    
    // 创建客服界面
    customer_scr = lv_obj_create(NULL);
    lv_obj_add_style(customer_scr, &bg_style, 0);
    
    // 创建标题
    lv_obj_t *title = lv_label_create(customer_scr);
    lv_label_set_text(title, "联系客服");
    lv_obj_set_style_text_font(title, font_chinese, 0);
    lv_obj_set_style_text_color(title, lv_color_white(), 0);
    lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 20);
    
    // 创建聊天区域
    chat_area = lv_obj_create(customer_scr);
    lv_obj_set_size(chat_area, LV_PCT(90), LV_PCT(60));
    lv_obj_align(chat_area, LV_ALIGN_TOP_MID, 0, 60);
    lv_obj_set_style_bg_opa(chat_area, LV_OPA_50, 0);
    lv_obj_set_style_border_width(chat_area, 0, 0);
    lv_obj_set_flex_flow(chat_area, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(chat_area, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_set_style_pad_all(chat_area, 10, 0);
    
    // 创建输入区域
    lv_obj_t *input_cont = lv_obj_create(customer_scr);
    lv_obj_set_size(input_cont, LV_PCT(90), LV_PCT(15));
    lv_obj_align(input_cont, LV_ALIGN_BOTTOM_MID, 0, -50);
    lv_obj_set_style_bg_opa(input_cont, LV_OPA_0, 0);
    lv_obj_set_style_border_width(input_cont, 0, 0);
    lv_obj_set_flex_flow(input_cont, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(input_cont, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    
    // 创建输入框
    input_ta = lv_textarea_create(input_cont);
    lv_obj_set_width(input_ta, LV_PCT(70));
    lv_obj_set_style_text_font(input_ta, font_chinese, 0);
    lv_textarea_set_placeholder_text(input_ta, "请输入您的问题...");
    lv_textarea_set_one_line(input_ta, true);
    // 添加事件回调，点击时显示键盘
    lv_obj_add_event_cb(input_ta, ta_event_cb, LV_EVENT_ALL, NULL);
    
    // 创建发送按钮
    send_btn = lv_btn_create(input_cont);
    lv_obj_set_size(send_btn, LV_PCT(20), 40);
    lv_obj_set_style_bg_color(send_btn, lv_color_hex(0x007ACC), 0);
    
    lv_obj_t *send_label = lv_label_create(send_btn);
    lv_label_set_text(send_label, "发送");
    lv_obj_set_style_text_font(send_label, font_chinese, 0);
    lv_obj_center(send_label);
    
    lv_obj_add_event_cb(send_btn, send_msg_event_cb, LV_EVENT_CLICKED, NULL);
    
    // 创建返回按钮
    back_btn = lv_btn_create(customer_scr);
    lv_obj_set_size(back_btn, 100, 50);
    lv_obj_align(back_btn, LV_ALIGN_BOTTOM_LEFT, 20, -10);
    lv_obj_set_style_bg_color(back_btn, lv_color_hex(0x666666), 0);
    
    lv_obj_t *back_label = lv_label_create(back_btn);
    lv_label_set_text(back_label, "返回");
    lv_obj_set_style_text_font(back_label, font_chinese, 0);
    lv_obj_center(back_label);
    
    lv_obj_add_event_cb(back_btn, return_to_main_cb, LV_EVENT_CLICKED, NULL);
    


     // 创建转人工按钮
    lv_obj_t *   people_btn = lv_btn_create(customer_scr);
    lv_obj_set_size(people_btn, 100, 50);
    lv_obj_align(people_btn, LV_ALIGN_BOTTOM_RIGHT, -20, -10);
    lv_obj_set_style_bg_color(people_btn, lv_color_hex(0x666666), 0);
    
    lv_obj_t *people_label = lv_label_create(people_btn);
    lv_label_set_text(people_label, "转人工");
    lv_obj_set_style_text_font(people_label, font_chinese, 0);
    lv_obj_center(people_label);
    
    lv_obj_add_event_cb(people_btn, people_cb, LV_EVENT_CLICKED, NULL);
    // 加载界面
    lv_scr_load(customer_scr);
    
    // 添加欢迎消息
    lv_obj_t *welcome_msg = lv_label_create(chat_area);
    lv_label_set_text(welcome_msg, "客服: 您好，我是购票系统客服，有什么可以帮助您的吗？");
    lv_obj_set_style_text_align(welcome_msg, LV_TEXT_ALIGN_LEFT, 0);
    lv_obj_set_style_text_color(welcome_msg, lv_color_hex(0x28A745), 0);
    lv_obj_set_style_text_font(welcome_msg, font_chinese, 0);
    lv_obj_set_width(welcome_msg, LV_PCT(100));


    // 创建键盘
    kb = lv_keyboard_create(customer_scr);
    lv_obj_set_size(kb, LV_HOR_RES, LV_VER_RES / 2);
    lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, 0);
    lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
    lv_obj_set_style_radius(kb, 10, 0);
    

    // //设置拼音
    // lv_obj_t * pinyin_ime = lv_ime_pinyin_create(customer_scr);
    // lv_obj_set_style_text_font(pinyin_ime, font_chinese, 0 );

    // lv_ime_pinyin_set_keyboard(pinyin_ime, kb); 
    //  /*设置候选框*/
    //     cand_panel = lv_ime_pinyin_get_cand_panel(pinyin_ime);
    //     lv_obj_set_parent(cand_panel, customer_scr); 
    //     lv_obj_set_size(cand_panel, LV_PCT(100), LV_PCT(10));
    //     lv_obj_align_to(cand_panel, kb, LV_ALIGN_OUT_TOP_MID, 0, 0);
    //     lv_obj_set_style_text_font(cand_panel, font_chinese, 0);  // 确保字体正确
    //     lv_obj_set_style_bg_color(cand_panel, lv_color_white(), LV_PART_MAIN);
    //     lv_obj_set_style_bg_opa(cand_panel, LV_OPA_COVER, LV_PART_MAIN);
    //     lv_obj_move_to_index(cand_panel, -1);

}